//
//  arcAssignEGAViewController.m
//  EGA_Archives_iOS
//
//  Created by gad on 1/11/56 BE.
//  Copyright (c) 2556 EGA. All rights reserved.
//
#define MAINLABEL_TAG 1
#define SECONDLABEL_TAG 2
#define PHOTO_TAG 3
#define NUMBER_OF_ROWS 3
#import "EGAAppDelegate.h"
#import "arcAssignEGAViewController.h"
#import "arcAssignDetailEGAViewController.h" 
#import "EGAarcAssignCell.h"
#import "EGAEmployeeInfo.h"//;
#import "mainEGAViewController.h"
#import "SVPullToRefresh.h"
#import <QuartzCore/QuartzCore.h>
#import "advanceSearch.h"
#import "ARC_DB.h"
#import "EGAUtility.h"

#define ROW_HEIGHT 80
#define CELL_WIDTH 650.0
#define LABEL_HEIGHT 50

//Lets define the dimensions of the two columns
//Set the column offset and the width.
#define NUMBER_OFFSET 10.0
#define NUMBER_WIDTH 50.0
#define NUMBER_TAG 1

#define TEXT_OFFSET 60.0
#define TEXT_WIDTH 270.0
#define TEXT_TAG 2

@interface arcAssignEGAViewController ()
{
    NSInteger countProperty;
}
 
@end


@implementation arcAssignEGAViewController

@synthesize chkPullOrInfinite;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

-(void)pull_refresh:(NSString*)Type
{
    ARC_DB * DB = [[ARC_DB alloc]init];
    if([DB internetConnected])
    {
        self.displaySourceArray =nil;
        [self.displaySourceArray  release];
        [DB saveAllBookListNew:Type];
        self.displaySourceArray = [DB getBooktest];
        countProperty=self.displaySourceArray.count ;
    }
    else
    {
         [self alertNotConnect];
    }
}

-(void)refresh
{
    ARC_DB * DB = [[ARC_DB alloc]init];
    if([DB internetConnected])
    {
        [DB saveAllBookListNew:@""];
        self.displaySourceArray =nil;
        [self.displaySourceArray  release];
        self.displaySourceArray = [DB getBooktest];
        countProperty=self.displaySourceArray.count ;
    }
    else
    {
        [self alertNotConnect];
    }
}

-(void)searchHide
{
    [UIView animateWithDuration:0.6 animations:^{
        
        [self.advanceSearch.view setFrame:CGRectMake(0, -400, 768, 300)];
    }];
    
    ;
}

-(void)searchShow
{
    [UIView animateWithDuration:0.6 animations:^{
        
        [self.advanceSearch.view setFrame:CGRectMake(0, 0, 768, 300)];
        
    }];
    
    
}
- (void)viewDidLoad
{
    
    [super viewDidLoad];
 
    
    self.advanceSearch = [[advanceSearch alloc]initWithNibName:@"advanceSearch" bundle:[NSBundle mainBundle]];
    self.advanceSearch.advanceDelegate = (id)self;
    [self.advanceSearch.view setFrame:CGRectMake(0, -300, 768, 300)];
    //[self.advanceSearch setMenuDelegate:self];
    [self.view addSubview:[self.advanceSearch view]];
    [self searchHide];
    ARC_DB * DB = [[ARC_DB alloc]init];
    // count equal zero
    if ([DB isHasBookInDB])
    {
         self.displaySourceArray = [DB getBooktest];
         countProperty=self.displaySourceArray.count;
    }
    else
    {
        [self refresh];
    }
    
    
    //EGAEmployeeInfo *emp=[[EGAEmployeeInfo alloc]init];

    
//    EGAarcAssignCell *item = [[EGAarcAssignCell alloc]init];
//    item.ID = 2;
//    item.Doc_FiscalYear =2;
//    item.Doc_Register = @"test" ;
//    item.Doc_Serial = @"test" ;
//    item.Doc_Subject =@"test" ;
//    item.Doc_Description = @"test" ;
//    item.Doc_date = @"test" ;
//    item.Doc_ReciveDate = @"test" ;
//    item.Doc_to = @"test" ;
//    item.DocToName = @"test" ;
//    item.Doc_Name = @"test" ;
//    item.Doc_Name = @"test" ;
//    item.Doc_Priority_ID =5 ;
//    item.Doc_priority_Name = @"test" ;
//    item.Doc_Secret_ID = 1 ;
//    item.Doc_Status_ID = @"test" ;
//    item.Doc_Status_Name =@"test" ;
//    item.chkAssign =1;
//    item.empEmail =@"test";
//    item.taskDetail = @"test" ;
//    item.DocPriorityID = @"test" ;
//    item.empEmail =@"test";
//    item.startDate = @"test" ;
//    item.IsDueDate = @"test" ;
//
//    item.DocBookBeforeSign_ID = @"test" ;
//    item.DocBookBeforeSign_Name = @"test" ;
//    item.DocAttachment_ID = @"test" ;
//    item.DocAttachment_Name = @"test" ;


 
    
 
    // setup pull-to-refresh
    [self.tableview addPullToRefreshWithActionHandler:^{
      // NSLog(@"refresh");
        
      //  [result addObject:item];
        
        int64_t delayInSeconds = 2.0;
        dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
        dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
            //[self.tableview beginUpdates];

            //[self refresh];
            
            chkPullOrInfinite = [[NSString alloc]initWithString:@"pull"];

            [self pull_refresh:@"upperID"];
            //countProperty=self.displaySourceArray.count ;

            //[self.tableview endUpdates];
            
            [self.tableview reloadData];
            [self.tableview.pullToRefreshView stopAnimating];
        });
    }];

    // setup infinite scrolling
    [self.tableview  addInfiniteScrollingWithActionHandler:^{
        
        int64_t delayInSeconds = 1;
        dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
        dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
           // [self.tableview beginUpdates];
        
            //[self.displaySourceArray addObject:[DB saveBook]];

            //countProperty=self.displaySourceArray.count ;
            
        
            [self pull_refresh:@"lowerID"];
            //countProperty=self.displaySourceArray.count ;
            
        
            //[self.tableview endUpdates];
            chkPullOrInfinite = [[NSString alloc]initWithString:@"infinite"];

            [self.tableview reloadData];
            [self.tableview.infiniteScrollingView stopAnimating];
        });
    }];

   contentView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
  //  contentView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 110, 30)];

    contentView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:.25];
        //activityLabel.frame = CGRectMake(370, 387, 70, 25);
    
   activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    
   
  //  activityIndicator.frame = CGRectMake(450, 384, 30, 30);
    activityIndicator = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake((self.view.frame.size.width/2) - 60, (self.view.frame.size.height/2) - 40, 150, 120)]; 
    activityIndicator.backgroundColor=[UIColor colorWithRed:105/255.0 green: 105/255.0 blue:105/255.0 alpha:1];
    [activityIndicator layer].cornerRadius = 8.0;
     [contentView addSubview:activityIndicator];

    activityLabel = [[UILabel alloc] init]; 
    activityLabel.text = NSLocalizedString(@"Loading", @"string1");
    activityLabel.textColor = [UIColor whiteColor];
    activityLabel.font = [UIFont boldSystemFontOfSize:17];
    activityLabel.backgroundColor=[UIColor clearColor];
    activityLabel.frame=CGRectMake((self.view.frame.size.width/2) - 60, (self.view.frame.size.height/2) -5, 150, 100);
    activityLabel.textAlignment = UITextAlignmentCenter;
    
    [contentView addSubview:activityLabel];
    [self.view addSubview:contentView];
    [self hideActivityView];
    _tableview.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
}
- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    [self.tableview deselectRowAtIndexPath:[self.tableview indexPathForSelectedRow] animated:NO];
    
    [super viewWillDisappear:animated];
    [activityIndicator stopAnimating];
}

-(void)viewWillAppear:(BOOL) animated {
    [super viewWillAppear:animated];
    [activityIndicator startAnimating];
}

//- (void)parseJsonMethod{
//    self.tableview.dataSource = self;
//    self.tableview.delegate = self;
//    NSString *jsonURL=[NSString stringWithFormat:@"http://%@ListBook.ashx",serviceUrl];
//	NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: [NSURL URLWithString: jsonURL]];
//    [request setHTTPMethod:@"POST"];
//    
//    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
//    // [request setHTTPBody:postData];
//	NSData *returnData = [NSURLConnection sendSynchronousRequest: request returningResponse: nil error: nil ];
//    if ([returnData length] == 0) {
//        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"ไม่สามารถเชื่อมต่อ server" message:@"กรุณาเช็คการเชื่อมต่อ" delegate:self cancelButtonTitle:@"ตกลง" otherButtonTitles: nil];
//        [alert show];
//        return;
//    }
//    [self.displaySourceArray removeAllObjects];
//    self.displaySourceArray = [EGAarcAssignCell arrayWithJson:returnData];
//    countProperty = self.displaySourceArray.count;
//
//}
//
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    //#warning Potentially incomplete method implementation.
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{ 
    if([chkPullOrInfinite isEqualToString:@"pull"])
    {
        return  countProperty ;
    }
    else //if (chkPullOrInfinite isEqualToString:@"infinite")
    {
        return [self.displaySourceArray count];
    }
    
    //return  countProperty ;
//    [_displaySourceArray count];
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    EGAarcAssignCell *info = [self.displaySourceArray objectAtIndex:indexPath.row];
    NSString  *Doc_Subject = info.Doc_Subject;
    NSInteger *ChkAssign   = info.chkAssign;
    NSString  *chkAssign_  =[NSString stringWithFormat:@"%d",ChkAssign];
    NSInteger *Doc_Priority_ID=info.Doc_Priority_ID;
    NSString  *Doc_Priority_ID_  =[NSString stringWithFormat:@"%d",Doc_Priority_ID];
    NSInteger *DocID   = info.ID;
    NSString  *DocID_  =[NSString stringWithFormat:@"%d",DocID];
//    NSString *DocToName = info.DocToName;
//    NSString *Org_Name = info.Org_Name;
//    NSString *Doc_Register = info.Doc_Register;
//    NSString *Doc_Serial = info.Doc_Serial;
//     NSString *Doc_Priority_ID=info.Doc_Priority_ID;
//   NSString *Doc_date = info.Doc_date;
   
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
    cell = [[UITableViewCell alloc]init];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle : UITableViewCellStyleSubtitle
                                      reuseIdentifier : @"Cell"];
    }
    
    
    //set dict
    //image and font
    //UIFont * font = [[UIFont alloc]init];
    if (([chkAssign_ isEqualToString:@"1"]) )
    {
        UIImageView * ivPriority = [[UIImageView alloc]initWithFrame:CGRectMake(10, 30, 40,40)];
        UIImage *img = [UIImage imageNamed:@"gavel.png"];
        [ivPriority setImage:img];
        [cell.contentView addSubview:ivPriority];
        
        //ลบ ใน ListNewBook ด้วย
        ARC_DB * DB = [[ARC_DB alloc]init];
        // count equal zero
        [DB deleteNewBookAssign:DocID_];
        //font = [UIFont systemFontOfSize:20];
    }
//    else if (([chkAssign_ isEqualToString:@"0"]) )
//    {
//        imgFolder.image=[UIImage imageNamed:@"status_noprocess.png"];
//        //font = [UIFont boldSystemFontOfSize:20];
//        
//    }
    
    
    //label
    UILabel *lblFrom     =[[UILabel alloc]initWithFrame:CGRectMake(65,20,520,30)];
    UILabel *lblDateGet     =[[UILabel alloc]initWithFrame:CGRectMake(610,10,200,30)];
    UILabel *lbltitle  =[[UILabel alloc]initWithFrame:CGRectMake(65,50,520,30)];

    //date
    NSString *str = info.Doc_ReciveDate;
    
//    NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
//    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
//    NSDate *date = [dateFormatter dateFromString: str];
//    dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
//    [dateFormatter setDateFormat:@"dd/MM/yyyy"];
//    NSString *convertedString = [dateFormatter stringFromDate:date];
    
    NSString *convertedString =@"";
    EGAUtility * Util = [[EGAUtility alloc]init];
    convertedString=[Util getDateTh:(str)];
    
    //convertedString=str;
    
    //add image
    if ([Doc_Priority_ID_ isEqualToString:@"1"])
    {
        UIImageView * ivPriority = [[UIImageView alloc]initWithFrame:CGRectMake(640,40,50,50)];
        UIImage *img = [UIImage imageNamed:@"flag_yellow.png"];
        [ivPriority setImage:img];
        [cell.contentView addSubview:ivPriority];
    }
    if ([Doc_Priority_ID_ isEqualToString:@"2"])
    {
        UIImageView * ivPriority = [[UIImageView alloc]initWithFrame:CGRectMake(640,40,40,40)];
        UIImage *img = [UIImage imageNamed:@"flag_red.png"];
        [ivPriority setImage:img];
        [cell.contentView addSubview:ivPriority];
    }
    if ([Doc_Priority_ID_ isEqualToString:@"3"])
    {
        UIImageView * ivPriority = [[UIImageView alloc]initWithFrame:CGRectMake(640,40,40,40)];
        UIImage *img = [UIImage imageNamed:@"flag_red.png"];
        [ivPriority setImage:img];
        [cell.contentView addSubview:ivPriority];
    }
    if ([Doc_Priority_ID_ isEqualToString:@"4"])
    {
        UIImageView * ivPriority = [[UIImageView alloc]initWithFrame:CGRectMake(640,40,40,40)];
        UIImage *img = [UIImage imageNamed:@"flag_red.png"];
        [ivPriority setImage:img];
        [cell.contentView addSubview:ivPriority];
    }
    
    
    lblFrom.text = [NSString stringWithFormat:@"จาก : %@", info.Org_Name];
    lbltitle.text=Doc_Subject;
    
    
    lblFrom.font = [UIFont systemFontOfSize:22];
    lbltitle.font = [UIFont systemFontOfSize:20];
    lblDateGet.text=convertedString;
    lblDateGet.font = [UIFont systemFontOfSize:20];
    
    lblFrom.textColor = [UIColor darkGrayColor];
    lbltitle.textColor = [UIColor darkGrayColor];
    lblDateGet.textColor = [UIColor darkGrayColor];
    
    
    [cell.contentView addSubview:lblFrom];
    [cell.contentView addSubview:lbltitle];
    [cell.contentView addSubview:lblDateGet];

    
    
//    static NSString *identifier = @"MyCell";
//	
//	UITableViewCell *cell = [self.tableview dequeueReusableCellWithIdentifier:identifier];
//	if(cell == nil)
//		cell = [self reuseTableViewCellWithIdentifier:identifier];
//
//	
//	UILabel *lbl = (UILabel *)[cell viewWithTag:1];
//    lbl.backgroundColor=[UIColor clearColor];
//	lbl.text = [NSString stringWithFormat:@"  %i. ", indexPath.row + 1];
//	
//	UILabel *l2 = (UILabel *)[cell viewWithTag:2];
//       l2.backgroundColor=[UIColor clearColor];
//    l2.text= [NSString stringWithFormat:@"%@%@\n%@%@\n%@%@" ,@"เรื่อง : ", Doc_Subject,@"ถึง : ", DocToName ,@"จาก : ", Org_Name];
//
//    
//    UILabel *l3 = (UILabel *)[cell viewWithTag:3];
//    l3.backgroundColor=[UIColor clearColor];
//    l3.text= [NSString stringWithFormat:@"%@%@\n%@%@" ,@"เลขเอกสารเข้ารับ : ", Doc_Register,@"เลขที่เอกสาร : ",  Doc_Serial ];
//
//    UILabel *l4 = (UILabel *)[cell viewWithTag:4];
//    l4.backgroundColor=[UIColor clearColor];
//    
//    NSLocale *usLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
//    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
//    [dateFormatter setDateFormat:@"dd-MM-YYYY"];
//    NSDate *dateFromString = [[NSDate alloc] init];
//    [dateFormatter setLocale:usLocale];
//     
//    l4.text=[dateFormatter stringFromDate:dateFromString];;
//    UILabel *l5 = (UILabel *)[cell viewWithTag:5];
//    l5.backgroundColor=[UIColor clearColor];
//    if (chkAssign==1)
//        l5.text=@"สังการแล้ว";
//    else
//        l5.text= @"-";
//

    return cell;
    

}
- (void)dealloc {

    [_table_view release];
 
    [self.tableview release];
    [self.displaySourceArray release];
 
    if (contentView != nil) [contentView release];
    if (activityLabel != nil) [activityLabel release];
    if (activityIndicator != nil) [activityIndicator release];
    
    [_btbAnimation release];
    [_advanSearch release];
   
    [_btBasicSearch release];
    [_txtBasicSearch release];
    [_txtBasicSearch release];
      [super dealloc];
}

-(NSIndexPath*) tableView: (UITableView*) tableView
 willSelectRowAtIndexPath: (NSIndexPath*) indexPath
{
    NSUInteger row = [indexPath row];
    NSMutableString *selectRow;
    selectRow = [NSMutableString stringWithFormat:@"Row: %d",[indexPath row]];
    return indexPath;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString * section = [NSString stringWithFormat:@"%d", indexPath.section];
    NSString * row = [NSString stringWithFormat:@"%d", indexPath.row];
        for (UIView *view in [self.view subviews])
        {
            [view removeFromSuperview];
        }
      EGAarcAssignCell *info = [self.displaySourceArray objectAtIndex:indexPath.row];
      arcAssignDetailEGAViewController *_arcAssignDetailEGAViewController  = [arcAssignDetailEGAViewController alloc];
      _arcAssignDetailEGAViewController.Doc_Subject=info.Doc_Subject;
      _arcAssignDetailEGAViewController.DocToName=info.DocToName;
      _arcAssignDetailEGAViewController.Org_Name=info.Org_Name;
      _arcAssignDetailEGAViewController.Doc_Register=info.Doc_Register;
      _arcAssignDetailEGAViewController.Doc_Serial=info.Doc_Serial;
      _arcAssignDetailEGAViewController.Doc_date=info.Doc_date;
    _arcAssignDetailEGAViewController.Doc_ReceiveDate=info.Doc_ReciveDate;
    _arcAssignDetailEGAViewController.Doc_Description=info.Doc_Description;
    _arcAssignDetailEGAViewController.Doc_Priority_Name=info.Doc_priority_Name;

    
    

    

    
      if ([info.empEmail isEqualToString:@"<null>"]) 
  
      _arcAssignDetailEGAViewController.empEmail=@"";
    else
        _arcAssignDetailEGAViewController.empEmail=info.empEmail; 
   

        _arcAssignDetailEGAViewController.Doc_Description=info.Doc_Description;
    
      _arcAssignDetailEGAViewController.ID=[NSString stringWithFormat:@"%d",info.ID];
   
    if ([info.taskDetail isEqualToString:@"<null>"])
        
        _arcAssignDetailEGAViewController.taskDetail=@"";
    else
          _arcAssignDetailEGAViewController.taskDetail=info.taskDetail;
    
     _arcAssignDetailEGAViewController.chkAssign=[NSString stringWithFormat:@"%d",info.chkAssign];
     _arcAssignDetailEGAViewController.Doc_Priority_Name=info.Doc_priority_Name;
      _arcAssignDetailEGAViewController.accessibilityLabel = [section stringByAppendingString:row];
    
    
     _arcAssignDetailEGAViewController.DocPriorityID=info.DocPriorityID;
     _arcAssignDetailEGAViewController.startDate=info.startDate;
     _arcAssignDetailEGAViewController.endDate=info.endDate;
     _arcAssignDetailEGAViewController.IsDueDate=info.IsDueDate;
    
    _arcAssignDetailEGAViewController.DocBookBeforeSign_ID = info.DocBookBeforeSign_ID;
    _arcAssignDetailEGAViewController.DocBookBeforeSign_Name = info.DocBookBeforeSign_Name;
    _arcAssignDetailEGAViewController.DocAttachment_ID = info.DocAttachment_ID;
    _arcAssignDetailEGAViewController.DocAttachment_Name = info.DocAttachment_Name;
    
//    _arcAssignDetailEGAViewController.DocBookBeforeSign_ID = @"x";
//    _arcAssignDetailEGAViewController.DocBookBeforeSign_Name = @"x";
//    _arcAssignDetailEGAViewController.DocAttachment_ID =@"x";
//    _arcAssignDetailEGAViewController.DocAttachment_Name = @"x";


//    NSLog(@"%@",info.DocBookBeforeSign_ID);
//    NSLog(@"%@",info.DocBookBeforeSign_Name);
//    NSLog(@"%@",info.DocAttachment_ID);
//    NSLog(@"%@",info.DocAttachment_Name);
    
    
      [self.view addSubview:_arcAssignDetailEGAViewController.view];

}
-(id)initWithFrame:(CGRect)theFrame {
    if (self = [super init]) {
        frame = theFrame;
        self.view.frame = theFrame;
    }
    return self;
}

-(void)showActivityView {
    if (contentView == nil) {
       // contentView = [[UIActivityViewController alloc] initWithFrame:self.view.superview.frame];
    }
    [self.view.superview insertSubview:contentView aboveSubview:self.view];
}

-(void)hideActivityView {
    //[contentView removeFromSuperView];
    [contentView performSelectorOnMainThread:@selector(removeFromSuperview) withObject:nil waitUntilDone:NO];
}

- (IBAction)actionHid:(id)sender {
    [self hideActivityView];
}
- (IBAction)actionShow:(id)sender {
     [self showActivityView];
}
- (IBAction)action:(id)sender {
    //[spinner stopAnimating];
}

-(void)alertNotConnect
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"ไม่สามารถเชื่อมต่อกับเซิฟเวอร์"
                                                    message:@"ทำให้ไม่สามารถอัพเดทข้อมูล"
                                                   delegate:nil
                                          cancelButtonTitle:@"OK"
                                          otherButtonTitles:nil];
    [alert show];
}
- (IBAction)search:(id)sender {
    [self searchShow];
}
- (IBAction)btSearch:(id)sender {
    //NSLog(@"search");
}
- (IBAction)basicSearch:(id)sender {
    [NSThread detachNewThreadSelector:@selector(showActivityView) toTarget:self withObject:nil ];
    self.tableview.dataSource = self;
    self.tableview.delegate = self;
    
//    NSString *jsonURL=[NSString stringWithFormat:@"http://%@ListBook.ashx",serviceUrl];
//	NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: [NSURL URLWithString: jsonURL]];
//    NSString * searchTextUTF8 = [_txtBasicSearch.text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
//    NSString *post = [NSString stringWithFormat:@"search=%@",  searchTextUTF8];
//    NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
//    NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];
//    [request setHTTPMethod:@"POST"];
//    [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
//    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
//    [request setHTTPBody:postData];
//	NSData *returnData = [NSURLConnection sendSynchronousRequest: request returningResponse: nil error: nil ];
    
    /////////////////new
    EGAUtility * Util = [[EGAUtility alloc]init];
    NSString * searchTextUTF8 = [_txtBasicSearch.text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSString *post = [NSString stringWithFormat:@"search=%@",searchTextUTF8];
    NSString *strURL=[NSString stringWithFormat:@"ws=ListBook.ashx&%@",post];
    NSData *returnData =[Util getDataFromService:strURL];
    /////////////////new
    
    /// เวลาค้นหา วันที่เพี้ยน ยังไม่ได้เช็ค
    
    
    
    if ([returnData length] == 0) {
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"ไม่สามารถเชื่อมต่อ server" message:@"กรุณาเช็คการเชื่อมต่อ" delegate:self cancelButtonTitle:@"ตกลง" otherButtonTitles: nil];
        [alert show];
        return;
    }
    //NSLog(@"jsonURL",jsonURL);
    [self.displaySourceArray removeAllObjects];
    self.displaySourceArray = [EGAarcAssignCell arrayWithJson:returnData];
    countProperty=self.displaySourceArray.count;
    [self.tableview reloadData];
    [self hideActivityView];
}
-(void)close{
      [self searchHide];
}
- (void)advanceSearch:(NSString *)textSearch:(NSString *)startDate:(NSString *)endDate:(NSString *)chkAssign{
    [self searchHide];
    // NSLog(@"xxx%@xxx%@xxx%@xxx%@",textSearch,startDate,endDate,chkAssign);
    [NSThread detachNewThreadSelector:@selector(showActivityView) toTarget:self withObject:nil ];
    self.tableview.dataSource = self;
    self.tableview.delegate = self;
    
    
    
//    NSString *jsonURL=[NSString stringWithFormat:@"http://%@ListBook.ashx",serviceUrl];
//	NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: [NSURL URLWithString: jsonURL]];
//   // NSString *post = [NSString stringWithFormat:@"search=%@",  _txtBasicSearch.text];
//    NSString *post = [NSString stringWithFormat:@"advanceSearch=%@&search=%@&sDate=%@&eDate=%@&chkAssign=%@",@"true",textSearch,startDate,endDate,chkAssign];
//    //NSLog(@"%@",post);
//    NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
//    NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];
//    [request setHTTPMethod:@"POST"];
//    [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
//    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
//    [request setHTTPBody:postData];
//    NSData *returnData = [NSURLConnection sendSynchronousRequest: request returningResponse: nil error: nil ];
    
    
    /////////////////new
    EGAUtility * Util = [[EGAUtility alloc]init];
    NSString *post = [NSString stringWithFormat:@"advanceSearch=%@&search=%@&sDate=%@&eDate=%@&chkAssign=%@",@"true",textSearch,startDate,endDate,chkAssign];
    NSString *strURL=[NSString stringWithFormat:@"ws=ListBook.ashx&%@",post];
    NSData *returnData =[Util getDataFromService:strURL];
    /////////////////new

    
    
    
    
    if ([returnData length] == 0) {
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"ไม่สามารถเชื่อมต่อ server" message:@"กรุณาเช็คการเชื่อมต่อ" delegate:self cancelButtonTitle:@"ตกลง" otherButtonTitles: nil];
        [alert show];
        return;
    }
    [self.displaySourceArray removeAllObjects];
    self.displaySourceArray = [EGAarcAssignCell arrayWithJson:returnData];
    countProperty=self.displaySourceArray.count;
    [self.tableview reloadData];
    [self hideActivityView];
}
@end

